// import store from '../store'
import { uploadTscParams } from '../api/param'
import { Message } from 'element-ui'
import { getMessageByCode } from '../utils/responseMessage'
import i18n from '../i18n/index'
export async function computedRelation (id) {
  let uploadData = await UploadTscParam(id)
  if (!uploadData) return
  let results = []
  let channel = uploadData.channelList
  // let channel = store.getters.globalParamModel.getParamsByType('channelList')
  let tableData = channel.map(item => {
    return {
      id: item.id,
      peddirection: item.realtype && item.realtype === 'peddirection' ? item.realdir : [],
      phasedirection: item.realtype && item.realtype === 'direction' ? item.realdir : []
    }
  })
  let colorArray = getDefaul(uploadData)
  tableData.forEach(itemA => {
    (uploadData.channelGreenConflictInfo.length > 0 ? uploadData.channelGreenConflictInfo : colorArray).forEach(itemB => {
      if (itemA.id === itemB.channelid) {
        // 处理peddirection
        if (itemA.peddirection !== undefined) {
          itemA.peddirection.forEach(pedDir => {
            if (pedDir > 0) {
              results.push({
                direction: pedDir,
                type: 'pedphase',
                laneConflictList: [],
                conflictchannel: itemB.greenconflict,
                pedConflictList: []
              })
            }
          })
        }

        // 处理phasedirection
        if (itemA.phasedirection !== undefined) {
          itemA.phasedirection.forEach(phaseDir => {
            if (phaseDir > 0) {
              results.push({
                direction: phaseDir,
                type: 'phase',
                conflictchannel: itemB.greenconflict,
                laneConflictList: [],
                pedConflictList: []
              })
            }
          })
        }
      }
    })
  })
  results.forEach(item => {
    item.conflictchannel.forEach(aaaValue => {
      channel.forEach(cha => {
        if (cha.id === aaaValue) {
          if (cha.realtype === 'direction') {
            if (cha.realdir) {
              item.laneConflictList.push(...cha.realdir)
            }
          } else if (cha.realtype === 'peddirection') {
            if (cha.realdir) {
              item.pedConflictList.push(...cha.realdir)
            }
          }
        }
      })
    })
    delete item.conflictchannel
  })
  // const uniqueDirections = new Set()
  // const doChange = results.filter(obj => {
  //   if (uniqueDirections.has(obj.direction)) {
  //     return false
  //   }
  //   uniqueDirections.add(obj.direction)
  //   return true
  // })
  const uniqueDirectionsAndTypes = new Set()
  const filteredResults = results.filter(obj => {
    const key = `${obj.direction}_${obj.type}`
    if (uniqueDirectionsAndTypes.has(key)) {
      return false
    }
    uniqueDirectionsAndTypes.add(key)
    return true
  })
  let result = filteredResults.map(item => {
    let uniqueLaneConflictList = [...new Set(item.laneConflictList)]
    let uniquePedConflictList = [...new Set(item.pedConflictList)]
    return {
      ...item,
      laneConflictList: uniqueLaneConflictList,
      pedConflictList: uniquePedConflictList
    }
  })
  console.log('result', result)
  return result
}
export function getDefaul (data) {
  let phaseList = data.phaseList
  let overlaplList = data.overlaplList
  let channel = data.channelList
  let newPhase = phaseList.map(item => {
    return {
      id: item.id,
      concurrent: item.concurrent
    }
  })
  let newOverlap = overlaplList.map(item => {
    return {
      id: item.id,
      includedphases: item.includedphases
    }
  })
  let newChannel = channel.map(item => {
    return {
      id: item.id,
      controltype: item.controltype,
      controlsource: item.controlsource
    }
  })
  let defaultList = newChannel.map(cha => {
    if (cha.controltype === 2 || cha.controltype === 3) {
      for (let i = 0; i < newPhase.length; i++) {
        if (cha.controlsource === newPhase[i].id) {
          return {
            id: cha.id,
            controlsource: cha.controlsource,
            newCurren: newPhase[i].concurrent
          }
        }
      }
    } else if (cha.controltype === 4 || cha.controltype === 5) {
      let newLap = newOverlap.map(item => {
        let phaList = []
        if (item.id === cha.controlsource) {
          phaList.push(...item.includedphases)
        }
        // for (let h = 0; h < item.includedphases.length; h++) {
        //   for (let k = 0; k < newPhase.length; k++) {
        //     if (item.includedphases[h] === newPhase[k].id) {
        //       phaList.push(...newPhase[k].concurrent)
        //     }
        //   }
        // }
        return {
          id: item.id,
          concurrent: Array.from(new Set(phaList))
        }
      })
      for (let i = 0; i < newLap.length; i++) {
        if (cha.controlsource === newLap[i].id) {
          return {
            id: cha.id,
            controlsource: newLap[i].concurrent,
            newCurren: newLap[i].concurrent
          }
        }
      }
    } else {
      return {
        id: cha.id,
        controlsource: cha.controlsource,
        newCurren: []
      }
    }
  })
  // this.colorArray = this.transform(defaultList)
  const ret = defaultList.map((i, idx) => {
    const result = []
    let greenconflict = []
    defaultList.forEach((j, jdx) => {
      if (idx !== jdx) {
        const ic = Array.isArray(i.controlsource) ? i.controlsource : [i.controlsource]
        const jc = Array.isArray(j.controlsource) ? j.controlsource : [j.controlsource]
        let hasDuplicate = false
        for (let i = 0; i < ic.length; i++) {
          for (let j = 0; j < jc.length; j++) {
            if (ic[i] === jc[j]) {
              hasDuplicate = true
              break
            }
          }
          if (hasDuplicate) {
            break
          }
        }
        const isRelation = ic.some(x => jc.some(y => newPhase.find(m => m.id === x && m.concurrent.includes(y))))
        if (isRelation || hasDuplicate) {
          result.push(j.id)
        } else {
          greenconflict.push(j.id)
        }
      }
    })
    i.result = result
    i.greenconflict = greenconflict
    return i
  })
  let newFlict = ret.map(r => {
    return {
      channelid: r.id,
      greenOther: r.result,
      greenconflict: r.greenconflict
    }
  })
  return newFlict
}
export function UploadTscParam (id) {
  return uploadTscParams(id).then(data => {
    if (!data.data.success) {
      if (data.data.code === '4002' && data.data.data.errorCode === '4209') {
        let success = data.data.data.content.success
        if (success !== 0) {
          let errormsg = 'openatccomponents.overview.putTscControlError' + success
          Message.error(this.$t(errormsg))
          return
        }
      }
      if (data.data.code === '4002') { // 错误应答
      // 子类型错误
        let childErrorCode = data.data.data.errorCode
        if (childErrorCode) {
          Message.error(getMessageByCode(data.data.data.errorCode, i18n.locale))
          return
        }
      }
      Message.error(getMessageByCode(data.data.code, i18n.locale))
      return
    }
    if (Object.keys(data.data.data.data).length === 0) {
      Message.error(this.$t('edge.errorTip.noSchemeUpload'))
      return
    }
    let {customInfo, ...allTscParam} = data.data.data.data
    if (allTscParam.manualpanel === undefined) {
      allTscParam.manualpanel = {}
    }
    if (allTscParam.channellock === undefined) {
      allTscParam.channellock = []
    }
    if (allTscParam.channelList === undefined) {
      allTscParam.channelList = []
    }
    if (allTscParam.overlaplList === undefined) {
      allTscParam.overlaplList = []
    }
    if (allTscParam.detectorList === undefined) {
      allTscParam.detectorList = []
    }
    if (allTscParam.pedestrainDetectorList === undefined) {
      allTscParam.pedestrainDetectorList = []
    }
    if (allTscParam.preemptList === undefined) {
      allTscParam.preemptList = []
    }
    if (allTscParam.channelGreenConflictInfo === undefined) {
      allTscParam.channelGreenConflictInfo = []
    }
    if (allTscParam.singleoptim === undefined) {
      allTscParam.singleoptim = []
    }
    return allTscParam
  })
}
